package org.hackystat.projectbrowser.page.settrigger;

import java.util.List;
import org.apache.wicket.PageParameters;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.CompoundPropertyModel;
import org.hackystat.ambientdevice.server.jaxb.Project;
import org.hackystat.ambientdevice.server.jaxb.Trigger;
import org.hackystat.ambientdevice.server.jaxb.TriggerActionPair;
import org.hackystat.projectbrowser.ProjectBrowserSession;

/**
 * The class form that edits a trigger's name.
 * 
 * @author rEdward Kim
 * 
 */
public class EditTriggerNameTable extends StatelessForm {

  /** Supports serialization. */
  private static final long serialVersionUID = 1L;

  private String oldTAPid;
  private String tempTriggerName;
  private String oldTriggerName;
  private String projectName;
  private PageParameters responseParam = new PageParameters();

  /**
   * The form that edits a trigger's name.
   * 
   * @param id A string that's passed to the super (not really needed).
   * @param tapId The current trigger/action pair name.
   * @param projectName The current project name.
   * @param oldTriggerName The old trigger name.
   */
  public EditTriggerNameTable(String id, String tapId, String projectName, String oldTriggerName) {
    super(id);
    this.oldTAPid = tapId;
    this.projectName = projectName;
    this.oldTriggerName = oldTriggerName;
    responseParam.add("projectName", this.projectName);
    responseParam.add("tapName", this.oldTAPid);

    setModel(new CompoundPropertyModel(this));
    add(new TextField("tempTriggerName"));
  }

  /**
   * When the form is submiting, check for errors and try to create a new project.
   */
  @Override
  public void onSubmit() {
    Project project = ProjectBrowserSession.get().getProjectTypeXMLByNameId(this.projectName);
    List<TriggerActionPair> pairs = project.getTriggerActionPairs().getTriggerActionPair();
    for (TriggerActionPair pair : pairs) {
      if (pair.getId().equals(this.oldTAPid)) {
        for (Trigger tempTrigger : pair.getTriggers().getTrigger()) {
          if (tempTrigger.getId().equals(this.oldTriggerName)) {
            tempTrigger.setId(tempTriggerName);
          }
        }
      }
    }

    // set response page to go back to chooseTAP
    setResponsePage(ChooseTrigger.class, responseParam);
  }

  /**
   * The setter for the temp trigger name.
   * 
   * @param tempTriggerName The temp trigger name.
   */
  public void setTempTriggerName(String tempTriggerName) {
    this.tempTriggerName = tempTriggerName;
  }

  /**
   * The setter for the temp trigger name.
   * 
   * @return The temp trigger name.
   */
  public String getTempTriggerName() {
    return this.tempTriggerName;
  }

}
